package com.biz.primus.ms.base.jpa.converter;

import com.biz.primus.common.utils.JsonUtils;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.persistence.AttributeConverter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by defei on 7/10/17.
 */
public class DefaultJsonConverter implements AttributeConverter<Object, String>, Serializable {

    @Override
    public String convertToDatabaseColumn(Object attribute) {

        if (attribute == null) {
            return null;
        } else {
            String dataType = attribute.getClass().getName();
            String dataJson = JsonUtils.obj2Json(attribute);
            Map<String, String> data = new LinkedHashMap<>();
            data.put(DATA_TYPE, dataType);
            data.put(DATA_JSON, dataJson);
            return JsonUtils.obj2Json(data);
        }
    }

    @Override
    public Object convertToEntityAttribute(String dbData) {

        if (StringUtils.isBlank(dbData)) {
            return null;
        } else {
            Map dataInfo = JsonUtils.json2Obj(dbData, Map.class);
            Object dateType = dataInfo.get(DATA_TYPE);
            Object dataJson = dataInfo.get(DATA_JSON);
            try {
                Class<?> aClass = Class.forName(dateType.toString());
                return JsonUtils.json2Obj(dataJson.toString(), aClass);
            } catch (Exception e) {
                logger.warn("Parse json data:{} failed.", dbData, e);
                return null;
            }
        }
    }

    private static final String DATA_TYPE = "dateType";

    private static final String DATA_JSON = "dataJson";

    private static final Logger logger = LoggerFactory.getLogger(DefaultJsonConverter.class);
}
